<script lang="ts" setup name="XtxNumbox">
import { getCurrentInstance,ComponentInternalInstance  } from 'vue'
let {proxy } = getCurrentInstance() as ComponentInternalInstance 
  //
 const props = defineProps({
    modelValue:{
      type:Number,
      default:1
    },
    min: {
    type: Number,
    default: 1,
  },
  max: {
    type: Number,
    default: 20,
  },
  label:{
    type:String,
    default:''
  }
  })
  const emit = defineEmits<{
    (e:'update:modelValue',v:number):void
  }>()
 
  //  加数
   const add = () => {
  if (props.modelValue >= props.max) return
  emit('update:modelValue', props.modelValue + 1)
  }
  // 减数
  const sub = () => {
    if (props.modelValue <= props.min) return
    emit('update:modelValue', props.modelValue - 1)
  }
  // 手动输入
  const changeCount = (e:Event)=>{
    const  el = e.target as HTMLInputElement //dom元素明确类型
    let value = +el.value //输入框的值
    // 限制输入非数字
    if(isNaN(value)) value=props.min
    // 限制最小值
    if(value<=props.min) value = props.min
    // 限制最大值
    if(value>=props.max) value = props.max
    //虚拟dom bug  强制更新
    proxy!.$forceUpdate()
    // 提交父组件
    emit('update:modelValue', value)
  }
  </script>
  <template>
    <div class="xtx-numbox">
      <div class="label" v-if="props.label">{{props.label}}</div>
      <div class="numbox">
        <a :class="{disabled:props.modelValue <= props.min}" href="javascript:;" @click="sub">-</a>
        <input type="text"   @input="changeCount" :value="modelValue" />
        <a :class="{disabled:props.modelValue >= props.max}" href="javascript:;" @click="add">+</a>
      </div>
    </div>
  </template>
  
  <style scoped lang="less">
  .xtx-numbox {
    display: flex;
    align-items: center;
    .label {
      width: 60px;
      color: #999;
      padding-left: 10px;
    }
    .numbox {
      width: 120px;
      height: 30px;
      border: 1px solid #e4e4e4;
      display: flex;
      > a {
        width: 29px;
        line-height: 28px;
        text-align: center;
        background: #f8f8f8;
        font-size: 16px;
        color: #666;
        &:first-of-type {
          border-right: 1px solid #e4e4e4;
        }
        &:last-of-type {
          border-left: 1px solid #e4e4e4;
        }
        &.disabled{
          cursor: not-allowed;
          background-color: #ccc;
        }
      }
      > input {
        width: 60px;
        padding: 0 5px;
        text-align: center;
        color: #666;
      }
    }
  }
  </style>